#!/bin/bash

# 环境工程咨询系统一键部署脚本 - 阿里云Linux版本
# 服务器: 8.137.120.76 (gzqhst.com)
# 项目: https://gitee.com/lizaoboss/gzqhsz.git
# 系统: Alibaba Cloud Linux 3.2104 LTS

set -e

echo "🚀 开始一键部署环境工程咨询系统 (阿里云Linux版)..."

# 检查系统版本
echo "📋 系统信息:"
cat /etc/os-release

# 更新系统
echo "📦 更新系统..."
dnf update -y

# 检查并配置EPEL仓库
echo "🔧 配置软件仓库..."
# 阿里云Linux通常已经有epel-aliyuncs-release，不需要额外安装epel-release

# 安装必要软件
echo "🔧 安装必要软件..."
dnf install -y python3 python3-pip git curl firewalld

# 安装Node.js和npm (使用NodeSource仓库获取最新版本)
echo "🔧 安装Node.js..."
curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
dnf install -y nodejs

# 安装Nginx
echo "🔧 安装Nginx..."
dnf install -y nginx

# 启动并启用firewalld
systemctl start firewalld
systemctl enable firewalld

# 配置防火墙
echo "🔒 配置防火墙..."
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload

# 配置pip国内镜像源
echo "🔧 配置pip国内镜像源..."
mkdir -p ~/.pip
cat > ~/.pip/pip.conf << 'EOF'
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
trusted-host = pypi.tuna.tsinghua.edu.cn
EOF

# 配置npm国内镜像源
echo "🔧 配置npm国内镜像源..."
npm config set registry https://registry.npmmirror.com

# 安装PM2
echo "📋 安装PM2..."
npm install -g pm2

# 克隆项目
echo "📥 克隆项目..."
mkdir -p /var/www
cd /var/www
if [ -d "environmental-consulting" ]; then
    rm -rf environmental-consulting
fi
git clone https://gitee.com/lizaoboss/gzqhsz.git environmental-consulting
cd environmental-consulting

# 运行项目部署脚本
echo "🏗️ 运行项目部署..."
chmod +x deploy.sh
./deploy.sh production

# 配置环境变量
echo "⚙️ 配置环境变量..."
cd backend
cat > .env << 'EOF'
# 数据库配置
DATABASE_URL=sqlite:///./environmental_consulting.db

# JWT密钥
SECRET_KEY=gzqhsz-environmental-consulting-super-secret-key-2024

# 应用配置
DEBUG=false
HOST=0.0.0.0
PORT=8001

# 前端URL
FRONTEND_URL=https://gzqhst.com
EOF

cd ..

# 配置后端环境变量
echo "⚙️ 配置后端环境变量..."
cd backend
cat > .env << 'EOF'
DATABASE_URL=sqlite:///./environmental_consulting.db
SECRET_KEY=gzqhsz-environmental-consulting-super-secret-key-2024
DEBUG=false
HOST=0.0.0.0
PORT=8001
FRONTEND_URL=https://gzqhst.com
EOF

cd ..

# 配置PM2
echo "🔄 配置PM2..."
cat > ecosystem.config.cjs << 'EOF'
module.exports = {
  apps: [
    {
      name: 'environmental-api',
      script: 'venv/bin/python',
      args: '-m uvicorn app.main:app --host 0.0.0.0 --port 8001',
      cwd: '/var/www/environmental-consulting/backend',
      env: {
        NODE_ENV: 'production',
        DATABASE_URL: 'sqlite:///./environmental_consulting.db',
        SECRET_KEY: 'gzqhsz-environmental-consulting-super-secret-key-2024',
        DEBUG: 'false',
        HOST: '0.0.0.0',
        PORT: '8001',
        FRONTEND_URL: 'https://gzqhst.com',
        PYTHONPATH: '/var/www/environmental-consulting/backend'
      },
      instances: 1,
      exec_mode: 'fork',
      watch: false,
      max_memory_restart: '1G',
      autorestart: true,
      error_file: '/var/www/environmental-consulting/logs/api-error.log',
      out_file: '/var/www/environmental-consulting/logs/api-out.log',
      log_file: '/var/www/environmental-consulting/logs/api-combined.log',
      time: true
    }
  ]
};
EOF

mkdir -p logs

# 停止现有PM2进程并启动新的
pm2 delete all 2>/dev/null || true
pm2 start ecosystem.config.cjs
pm2 save
pm2 startup --hp /root

# 创建SSL目录并配置证书
echo "🔐 配置SSL证书..."
mkdir -p /etc/nginx/ssl

# 配置Nginx
echo "🌐 配置Nginx..."
cat > /etc/nginx/conf.d/environmental-consulting.conf << 'EOF'
# HTTP服务器 - 重定向到HTTPS
server {
    listen 80;
    server_name gzqhst.com;
    return 301 https://$server_name$request_uri;
}

# HTTPS服务器
server {
    listen 443 ssl http2;
    server_name gzqhst.com;

    # 设置客户端最大请求体大小，支持文件上传
    client_max_body_size 35M;

    # SSL证书配置
    ssl_certificate /etc/nginx/ssl/gzqhst.com.pem;
    ssl_certificate_key /etc/nginx/ssl/gzqhst.com.key;

    # SSL安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 前端静态文件
    location / {
        root /var/www/environmental-consulting/dist/static;
        try_files $uri $uri/ /index.html;

        # 缓存静态资源
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # API代理
    location /api/ {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 文件上传和静态文件
    location /uploads/ {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /images/ {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # API文档
    location /docs {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /redoc {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
}
EOF

# 禁用默认站点
rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true

# 测试Nginx配置
nginx -t
systemctl restart nginx
systemctl enable nginx

echo "✅ 部署完成！"
echo ""
echo "🌐 访问地址:"
echo "   - 网站首页: https://gzqhst.com"
echo "   - API文档: https://gzqhst.com/docs"
echo ""
echo "🔑 默认管理员账户:"
echo "   - 用户名: admin"
echo "   - 密码: admin123"
echo ""
echo "🔧 管理命令:"
echo "   - 查看服务: pm2 status"
echo "   - 重启服务: pm2 restart environmental-api"
echo "   - 查看日志: pm2 logs environmental-api"
echo ""
echo "🔐 SSL证书配置:"
echo "   请将SSL证书文件上传到 /etc/nginx/ssl/ 目录："
echo "   - gzqhst.com.pem"
echo "   - gzqhst.com.key"
echo "   然后重启Nginx: systemctl reload nginx"
echo ""
echo "🎉 祝您使用愉快！"
